var Index = {
  config: {
    myShakeEvent : null 
  },
  
  init: function (config) {
    var _this = this;
    $.extend(_this.config, config);
    
    _this.config.myShakeEvent = new Shake({
        threshold: 15
    });
    _this.listen_shake();
    
    
    $(document).on('click' , '#hand' , function(e){
      e.preventDefault();
      shake_detected();
    });

    //关闭弹窗
    $(document).on('click' , '.modal-bg' , function(e){
      e.preventDefault();
      My_Modal.hide('award_modal');
      Index.listen_shake();
    });

  },
  
  listen_shake: function () {
    var _this = this;
    _this.config.myShakeEvent.start();
    window.addEventListener('shake', shake_detected, false);
  },
  
  stop_listen_shake: function () {
    var _this = this;
    _this.config.myShakeEvent.stop();
    window.removeEventListener('shake', shake_detected, false);
  },
};

var shake_detected =  function () {
  Index.stop_listen_shake();
  $('#sound')[0].play();

  $('#hand').removeClass().addClass('wobble animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
    $(this).removeClass();
    var url = Index.config.do_lottery_url ;
    var data = {
      user_id : Index.config.user_id ,
    };
    $.post( url ,  data , function(ret){
      
      if ( !ret.status ) {
        tips( ret.info );
        return ;
      }
      
      var award_data = ret.data ;
      $('#award_icon').attr('src' , get_domain() + award_data.icon );

      if ( award_data.type == 99 ) {
        $('#award_type').html('运气不佳啊，请再试一次');
        $('#award_name').html('');
      } else {
        $('#award_type').html('恭喜你获得');
        $('#award_name').html(award_data.name);

        if ( award_data.type == 1 ) {
          $('#award_link').attr('href' , award_data.sn_url );
        } else {
          $('#award_link').attr('href' , '#' );
        }
        
      }
      
      My_Modal.show('award_modal' , true );
    });
  });
}

var My_Modal = {
  show : function( id , pos ){
    if ( $('.modal-bg').length == 0 ) {
      $('body').append('<div class="modal-bg"></div>');
      $('.modal-bg').height($(document).height());
    }
    $('.modal-bg').show();
    
    if ( !empty(pos) ) {
      this.set_pos( id );
    }
    $('#'+ id).show();
  },
  hide : function( id ){
    $('.modal-bg').hide();
    $('#'+ id).hide();
  },
  
  set_pos:function( id ) {
    var left = ( $(window).width() - $('#'+id).width() ) / 2 ;
    var top = ( $(window).height() - $('#'+id).height() ) / 2 ;
    $('#'+id).css({
      left : left + 'px' ,
      top : top + 'px' 
    });
  }
} 